import { useState, useEffect } from 'react';
import { Tool } from '../types/tool';
import { defaultTools } from '../data/tools';

const STORAGE_KEY = 'dtsetoolbox_tools';

export function useTools() {
  const [tools, setTools] = useState<Tool[]>([]);

  // 从localStorage加载工具
  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      try {
        const parsedTools = JSON.parse(stored);
        setTools(parsedTools);
      } catch (error) {
        console.error('Failed to parse stored tools:', error);
        setTools(defaultTools);
      }
    } else {
      setTools(defaultTools);
    }
  }, []);

  // 保存工具到localStorage
  const saveTools = (newTools: Tool[]) => {
    setTools(newTools);
    localStorage.setItem(STORAGE_KEY, JSON.stringify(newTools));
  };

  // 添加工具
  const addTool = (tool: Omit<Tool, 'id'>) => {
    const newTool: Tool = {
      ...tool,
      id: generateId(),
      createdAt: new Date().toISOString(),
    };
    saveTools([...tools, newTool]);
  };

  // 更新工具
  const updateTool = (id: string, updates: Partial<Tool>) => {
    const newTools = tools.map(tool =>
      tool.id === id ? { ...tool, ...updates } : tool
    );
    saveTools(newTools);
  };

  // 删除工具
  const deleteTool = (id: string) => {
    const newTools = tools.filter(tool => tool.id !== id);
    saveTools(newTools);
  };

  // 重置为默认工具
  const resetToDefaults = () => {
    saveTools(defaultTools);
  };

  return {
    tools,
    addTool,
    updateTool,
    deleteTool,
    resetToDefaults,
  };
}

// 生成唯一ID
function generateId(): string {
  return `tool_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}


